import { _decorator, Component, sys } from "cc";
const { ccclass, property } = _decorator;

interface UserData {
  name: string;
  registerTime: string;
  updateTime: string;
  identify: string;
  score: number;
}

@ccclass("StorageKit")
export class StorageKit extends Component {
  storageIdentify: string = "ChriotCombat";

  storeUserData(
    userName: string,
    registerTime: string = "",
    updateTime: string = "",
    score: number = 0
  ) {
    const userData: UserData = {
      name: userName,
      registerTime: registerTime,
      updateTime: updateTime,
      identify: this.storageIdentify,
      score: score,
    };
    const jsonStr = JSON.stringify(userData);
    sys.localStorage.setItem(userName, jsonStr);
  }

  obtainTargetUser(userName: string) {
    const jsonStr = sys.localStorage.getItem(userName);
    const userData = JSON.parse(jsonStr) as UserData;
    return userData;
  }

  obtainAllUser() {
    const allKeys = [];
    const allValues = [];

    // 获取所有存储的键
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key) {
        const value = localStorage.getItem(key);
        try {
          // 尝试将 value 解析为 JSON 对象
          const parsedValue = JSON.parse(value);
          // 检查是否包含 "identify" 属性,并且该属性的值是否等于 this.storageIdentify
          if (parsedValue.identify === this.storageIdentify) {
            allKeys.push(key);
            allValues.push(value);
          }
        } catch (error) {
          // 如果解析失败,忽略该值
          console.info(`Failed to parse value for key "${key}":`, error);
        }
      }
    }

    // 返回键值对数组
    const kvArray: any[] = allKeys.map((key, index) => ({
      key,
      value: allValues[index],
    }));

    return kvArray;
  }
}
